/**********************************************************************
 *
 * $RCSfile: AbstractEventChannel.java,v $  $Revision: 1.1 $  $Date: 2009/08/09 08:00:56 $
 *
 * $Log: AbstractEventChannel.java,v $
 * Revision 1.1  2009/08/09 08:00:56  @author simplefan
 * *** empty log message ***
 *
 *
 *
 *********************************************************************/
/*
 * Copyright 2008 gxlu, Inc. All rights reserved.
 * File name : AbstractEventChannel.java
 * Created on : Jul 30, 2009 2:31:46 AM
 * Creator : lethe
 */
package com.simplefan.meta.eda;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * Description : TODO
 * @author simplefan
 * </pre>
 */
public abstract class AbstractEventChannel implements EventChannel {

  private Map<EventType, List<EventListener>> eventTypeListener = new HashMap<EventType, List<EventListener>>();

  public List<EventListener> getListener(EventType eventType) {
    List<EventListener> ret = new ArrayList<EventListener>();
    List<EventListener> classList = eventTypeListener.get(eventType);
    if(classList != null && classList.size() > 0) {
      ret.addAll(classList);
    }
    return ret;
  }

  public synchronized void subscribe(EventListener listener, EventType eventType) {
    List<EventListener> classList = eventTypeListener.get(eventType);
    if(classList == null) {
      classList = new ArrayList<EventListener>();
      eventTypeListener.put(eventType, classList);
    }
    if(!classList.contains(listener)) {
      classList.add(listener);
    }
  }

  public void unsubscribe(EventListener listener, EventType eventType) {
    List<EventListener> objectList = eventTypeListener.get(eventType);
    if(objectList != null && objectList.size() > 0) {
      Iterator<EventListener> iter = objectList.iterator();
      for(Iterator<EventListener> iterator = iter; iterator.hasNext();) {
        EventListener eventListener = iterator.next();
        if(eventListener.equals(listener)) {
          iterator.remove();
          break;
        }

      }
    }
  }

  public List<EventType> getSubscribeEventTypeList() {
    if(eventTypeListener.size() > 0) {
      List<EventType> ret = new ArrayList<EventType>();
      ret.addAll(eventTypeListener.keySet());
      return ret;
    }
    else {
      return null;
    }
  }
}
